package com.pds.mvc;

import java.io.IOException;

import javax.servlet.ServletConfig;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.log4j.Logger;

public class ServletAction extends HttpServlet {
	public static Logger logger = Logger.getLogger(ServletAction.class);
	
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -5691899108844882376L;



	@Override
	public void init(ServletConfig config) throws ServletException {
		  // 获得工程根目录  
        String realPath =config.getServletContext().getRealPath("/"); 
        
        String mockStrutsCfgFile=config.getInitParameter("configFile");
        
        
        //获取配置文件路径，相当于struts.xml文件一样的作用  
        // 组合配置文件全物理路径
        mockStrutsCfgFile=realPath+mockStrutsCfgFile;
        config.getServletContext().setAttribute("mockStrutsCfgFile", mockStrutsCfgFile);  
	}
	
	
	
	
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		process(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		process(req, resp);
	}

	
	
	public void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
	// 获取地址栏中URL  
        String requestUrl = request.getServletPath();  
      // 取得下一个处理请求的Servlet名
        String servletName =  requestUrl.substring(requestUrl.indexOf("/")+1, requestUrl.indexOf("."));
        
     // 以Servlet名为基础从设定文件中取得响应的Servlet类名
        ServletFinder finder = new ServletFinder(request.getSession().getServletContext().getAttribute("mockStrutsCfgFile").toString(), servletName);
        
         
        try {
        	 // 通过反射调用真正的Servlet类进行处理
        	String servletClass=finder.getServletClass();
			Actions actions  = (Actions) Class.forName(servletClass).newInstance();
			
		     // 执行execute给中ActionForward中的key赋值, 相当于struts中执行action作用  
	        ActionForward actionForward = actions.execute(request, response);  
	        // 执行中转  
	        if(actionForward!=null)  actionForward.forward(request, response);  
	    	  	
	       
			
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			logger.debug("servlet-conifig not found class------------");
			e.printStackTrace();
		}  catch (NullPointerException e) {
			e.printStackTrace();
			logger.debug("servletClass is nulll servlet-config xml中无此请求------------");
		}   
   
      
	}
	
	
	
	@Override
	public void destroy() {
	
		super.destroy();
	}
}
